package com.util.json;

import com.util.reflex.StudentGirl;

import java.lang.reflect.Field;
import java.sql.BatchUpdateException;
import java.util.List;

/**
 * JSON字符串封装工具
 */
public class Result {
    public  final static int OK = 1001;
    public final static int FIAL = 1005;
    //几组参数类型供比较
    public static  Class string = String.class;
    public static Class int1 = java.lang.Integer.class;
    public static Class int2 = int.class;
    public static Class bool = Boolean.class;
    public static  Class bool2 = boolean.class;
    //List 型
    public static Class listzz = List.class;
    /**
     * 转字符串 测试方法
     * @return
     */
    public static String tostring(){
        int status = 1001;
        String message = "哈哈哈哈";
        StudentGirl girl = new StudentGirl("小妹妹",18);
        StringBuffer buffer = new StringBuffer();
        //status
        buffer.append("{\"status\":")
                .append(status);
        //girl對象
        buffer.append(",\"girl\":{")
                .append("\"name\":")
                .append("\"")
                .append(girl.getName())
                .append("\"")
                .append(",\"age\":")
                .append(girl.getAge())
                .append("}");
                ///message
        buffer.append(",\"message\":")
                .append("\"")
                .append(message)
                .append("\"}");
        return buffer.toString();


    }

    /**
     * 对象转json
     * @param object
     * @return
     */
    public static String objectJson(Object object){


        StringBuffer buffer = new StringBuffer();
        //将对象转换在String对象
        Class c = object.getClass();


        Field[] fields = c.getDeclaredFields();
        //添加对象
        buffer.append("{");
        try {
          for(int i = 0;i<fields.length;i++){
              Field f = fields[i];
                f.setAccessible(true);//禁止java语言检查
              //除了首尾字段，中间字段都需要加上“，”号
                //判断类型 根据类型添加字段 判断是否为空
                //添加健
              if(i==0 ) {
                  buffer.append("\"")
                          .append(f.getName())
                          .append("\":");
              }else{
                  buffer.append(",\"")
                          .append(f.getName())
                          .append("\":");
              }
              //null型  首先要判断空型 不然后面要报错
              if(null == f.get(object) || "".equals(f.get(object))){
                  buffer.append(f.get(object));

              }
                //stirng类型
               else if(string.equals(f.getType())){
                           buffer .append("\"")
                          //要将双引号的替换成单引号，否则 转换成json 显示不出来。
                                   .append(((String)f.get(object)).replace("\"","\'"))
                           .append("\"");

                }
                //Int型
                else if(int1.equals(f.getType() ) || int2.equals(f.getType())){
                            buffer.append(f.get(object));
                }
                //bool型
                else if(bool.equals(f.getType()) || bool2.equals(f.getType()) ){
                    buffer.append(f.get(object));
                }

            }
        } catch (Exception e) {
            throw new RuntimeException("获取对象字段失败:"+e.getMessage());

        }
        buffer.append("}");

        return buffer.toString();
    }

    /**
     * 普通参数转JSON
     * @param value
     * @return
     */
    public static String paramJson(String key,Object value){
        StringBuffer buffer = new StringBuffer();
        buffer.append("\"")
        .append(key)
        .append("\":");
        Class c  = value.getClass();
        if(string.equals(c)){
            buffer.append("\"")
                    .append(value)
                    .append("\"");
        }else{
            buffer.append(value);
        }


        return  buffer.toString();
    }



    /**
     * 添加符号
     * 可以在JSON对象的前后任意位置插入任意符号
     * @param flag 符号
     * @param json json字符串
     * @param headOrTail 指定位置  1：头 2:尾
     */
    public static String addFlag(String flag,String json,int headOrTail){
        StringBuffer buffer = new StringBuffer();
        //头部插入
        if(headOrTail == 1){
            buffer.append(flag).append(json);
        }
        //尾部插入
        else{
            buffer.append(json).append(flag);
        }

        return buffer.toString();
    }

    /**
     * 在json字符中头尾都加上符号
     * @param json
     * @param
     * @return
     */
    public static String addFlagAll(String json){
        StringBuffer buffer = new StringBuffer();
        buffer.append("{")
                .append(json)
                .append("}");
        return buffer.toString();
    }

    /**
     * 可以转换实体与集合，还有基本变量，不能转换模型数据
     * 请求成功返回对象
     * 返回对象转换JSON
     * 转换逻辑
     * 1.判断对象是基本变量还是实体，分别调用不同的的转换方法
     * 然后再进行组合
     * 组合成 status ,message ,data.
     * @param object
     * @return
     */
    public static String successObj(Object object){

        StringBuffer buffer = new StringBuffer();
        String datas = ""; //返回参数
        Class clazz = object.getClass();
        //基本参数
        if(string.equals(clazz)
                || int1.equals(clazz)
                || int2.equals(clazz)
                || bool.equals(clazz)
                || bool2.equals(clazz)){
            datas =  paramJson("datas",object);
        }
        // List集合
        else if(clazz.getTypeName().contains("List")){
            datas = ListToJson((List<Object>)object);
        }
        //实体
        else{

            datas = objectJson(object);
        }
        String news = paramJson("message","请求成功");
        String status = paramJson("status",OK);
        //组合
        buffer.append(status)
                .append(",")
                .append(news)
                .append(",")
                .append("\"datas\":")
                .append(datas);
        //加上｛｝返回
        return addFlagAll(buffer.toString());
    }

    /**
     * 模型数据
     * @param object
     * @return
     */
    public static String successModelObj(Object object){

        StringBuffer buffer = new StringBuffer();
       StringBuilder datas = new StringBuilder(); //返回参数
        Class cla = object.getClass();
        Field[] field = cla.getDeclaredFields();
        try{
        for(int i = 0;i<field.length;i++){
            field[i].setAccessible(true);
            Class clazz = field[i].getType();
            //基本参数
            if(string.equals(clazz)
                    || int1.equals(clazz)
                    || int2.equals(clazz)
                    || bool.equals(clazz)
                    || bool2.equals(clazz)){
                datas .append(  paramJson(field[i].getName(),field[i].get(object)));
            }
            // List集合
            else if(clazz.getTypeName().contains("List")){
                datas.append(String.format("\"%s\":%s"
                        ,field[i].getName()
                        ,ListToJson((List<Object>)field[i].get(object))));

            }
            //实体
            else{
                datas.append(String.format("\"%s\":%s"
                        ,field[i].getName()
                        ,field[i].get(object)));
            }
            //只有1条数据不加","  多条数据 末尾不加"，"
            
            if(i != field.length-1){
                datas.append(",");
            }
        }}catch (Exception e){
            e.printStackTrace();
        }

        String news = paramJson("message","请求成功");
        String status = paramJson("status",OK);
        //组合
        buffer.append(status)
                .append(",")
                .append(news)
                .append(",")
                .append("\"datas\":{")
                .append(datas)
                .append("}");

        //加上｛｝返回
        return addFlagAll(buffer.toString());
    }

    /**
     * 集合 可以用successObj 代替
     * @param
     * @return
     */
    public static String successListObj(List listObj){

        StringBuffer buffer = new StringBuffer();
        String datas = ListToJson(listObj); //返回参数

        String news = paramJson("message","请求成功");
        String status = paramJson("status",OK);
        //组合
        buffer.append(status)
                .append(",")
                .append(news)
                .append(",")
                .append("\"datas\":")
                .append(datas);
        //加上｛｝返回
        return addFlagAll(buffer.toString());
    }
    /**
     * 请求成功 无返回对象
     * @return
     */
    public static String success(){
        StringBuffer buffer = new StringBuffer();
        String news = paramJson("message","请求成功");
        String status = paramJson("status",OK);
        buffer.append(status)
                .append(",")
                .append(news);
        return addFlagAll(buffer.toString());
    }

    /**
     * 带 消息 的返回
     * @param message
     * @return
     */
    public static String success(String message){
        StringBuffer buffer = new StringBuffer();
        String news = paramJson("message",message);
        String status = paramJson("status",OK);
        buffer.append(status)
                .append(",")
                .append(news);
        return addFlagAll(buffer.toString());
    }


    /**
     * 请求失败
     * @return
     */
    public static String fial(String message){
        StringBuffer buffer = new StringBuffer();
        String news = paramJson("message",message==null?"请求失败":message); //三元判断
        String status = paramJson("status",FIAL);
        buffer.append(status)
                .append(",")
                .append(news);
        return addFlagAll(buffer.toString());
    }

    /**
     * List 转json
     * @param listObj
     * @return
     */
    public static String ListToJson(List listObj){
        StringBuilder builder = new StringBuilder();
        builder.append("[");
        for(int i = 0 ;i<listObj.size();i++){
            if(i == listObj.size()-1){
                builder.append(objectJson(listObj.get(i)));
            }else{
                builder.append(objectJson(listObj.get(i))).append(",");
            }
        }
        builder.append("]");
        return builder.toString();
    }
    public static void main(String[] args) {
        //System.out.println(tostring());
        StudentGirl  girl = new StudentGirl("小姐奶",18);
        System.out.println(objectJson(girl));
        String name = "张王子";
        int age = 14;
        boolean b = true;
        String n = "";


        System.out.println(paramJson("message","我很好"));

        String status = paramJson("status", Result.OK);
        String param = paramJson("param","今天真的不错");
        String message = paramJson("message","成功");
        String g = objectJson(girl);
        StringBuffer buffer = new StringBuffer();
        buffer.append(status)
                .append(",")
                .append(param)
                .append(",")
                .append(g)
                .append(",")
                .append(message);
        System.out.println(addFlagAll(buffer.toString()));
        System.out.println(  successObj(girl));
    }

}
